﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Configuration;

namespace WeakEndForum
{
    public partial class TopicPage : System.Web.UI.Page
    {
        int tID = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            string getURIParam = "";
            if (Modules.isRequestedQueryStringValid("tID", "ID", "Sujets", out getURIParam))
            {
                if (Session["messagePostSuccess"] != null)
                {
                    literMessageSuccess.Text = "<p class=\"alert alert-success\">Votre message a été publié avec succès !</p>";
                    Session["messagePostSuccess"] = null;
                }
                tID = Convert.ToInt32(getURIParam);
                OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings[Constantes.DB_NAME].ConnectionString);
                conn.Open();

                OleDbCommand getPostInfos = new OleDbCommand("SELECT Titre, Ferme FROM Sujets WHERE ID = @tID", conn);
                getPostInfos.Parameters.Add(new OleDbParameter("tID", tID) { OleDbType = OleDbType.Integer });
                getPostInfos.Prepare();
                OleDbDataReader infoReader = getPostInfos.ExecuteReader();
                infoReader.Read();
                lblPostTitle.Text = (string)infoReader[0];
                if ((bool)infoReader[1])
                {
                    btnToggleSujet.Text = "Ouvrir le sujet";
                    txtNewMessageContent.Enabled = false;
                    btnNewMessage.Enabled = false;
                }

                OleDbCommand postContent = new OleDbCommand("SELECT Messages.Contenu, Messages.Date_Creation, Messages.Auteur, Utilisateurs.Image_Avatar, Messages.ID FROM Utilisateurs INNER JOIN Messages ON Utilisateurs.Username = Messages.Auteur WHERE Messages.Sujet = @tID ORDER BY Messages.Date_Creation ASC;", conn);
                postContent.Parameters.Add(new OleDbParameter("tID", tID) { OleDbType = OleDbType.Integer });
                postContent.Prepare();
                OleDbDataReader dataReader = postContent.ExecuteReader();
                while (dataReader.Read())
                {
                    int mID = Convert.ToInt32(dataReader[4]);
                    TableRow row = new TableRow();
                    TableCell authorCell = new TableCell();
                    TableCell messageCell = new TableCell();
                    HyperLink Edit = new HyperLink();
                    Edit.CssClass = "blockElement";
                    Edit.Text = "Edit";
                    Edit.NavigateUrl = "EditMessage.aspx?mID=" + mID.ToString();
                    authorCell.CssClass = "postSection postAuthorSection";
                    Label userLabel = new Label();
                    userLabel.Text = (string)dataReader[2];
                    Image userAvatar = new Image();
                    userAvatar.ImageUrl = "~/User_Data/images/" + (string)dataReader[3];
                    userAvatar.CssClass = "thumbnail postImage";
                    TimeSpan timeSincePosted = DateTime.Now - (DateTime)dataReader[1];
                    Label timeSpanLabel = new Label();
                    timeSpanLabel.Text = "Publié il y a " + timeSincePosted.Days.ToString() + " jour(s), " + timeSincePosted.Hours.ToString() + " heure(s), " + timeSincePosted.Minutes.ToString() + " min., " + timeSincePosted.Seconds.ToString() + " sec.";
                    authorCell.Controls.Add(userLabel);
                    authorCell.Controls.Add(userAvatar);
                    authorCell.Controls.Add(timeSpanLabel);
                    if (Modules.getConnectedUser() == (string)dataReader[2])
                    {
                        authorCell.Controls.Add(Edit);
                    }
                    messageCell.CssClass = "postSection postMessageSection";
                    messageCell.Text = (string)dataReader[0];
                    row.Cells.Add(authorCell);
                    row.Cells.Add(messageCell);
                    postTable.Rows.Add(row);
                }
                conn.Close();
            }
            else
            {
                Server.Transfer("Error404.aspx");
            }

        }

        protected void btnNewMessage_Click(object sender, EventArgs e)
        {
            if (!Modules.isUserConnected())
            {
                Server.Transfer("Error401.aspx");
            }
            else
            {
                OleDbConnection connexion = new OleDbConnection(ConfigurationManager.ConnectionStrings[Constantes.DB_NAME].ConnectionString);
                connexion.Open();

                OleDbCommand getTopicStatus = new OleDbCommand("SELECT Ferme FROM Sujets WHERE ID = @tID", connexion);
                getTopicStatus.Parameters.Add(new OleDbParameter("tID", tID) { OleDbType = OleDbType.Integer });
                getTopicStatus.Prepare();
                OleDbDataReader statusReader = getTopicStatus.ExecuteReader();
                statusReader.Read();

                if (!(bool)statusReader[0])
                {
                    string newMessageContent = txtNewMessageContent.Text;
                    string newMessageAuthor = Modules.getConnectedUser();
                    OleDbCommand newPostMessage = new OleDbCommand("INSERT INTO Messages (Contenu, Auteur, Sujet) VALUES (@content, @author, @subject)", connexion);
                    newPostMessage.Parameters.Add(new OleDbParameter("content", newMessageContent) { OleDbType = OleDbType.VarChar, Size = 255 });
                    newPostMessage.Parameters.Add(new OleDbParameter("author", newMessageAuthor) { OleDbType = OleDbType.VarChar, Size = 255 });
                    newPostMessage.Parameters.Add(new OleDbParameter("subject", tID) { OleDbType = OleDbType.Integer });
                    newPostMessage.ExecuteNonQuery();
                    connexion.Close();
                    Session["messagePostSuccess"] = true;
                    Response.Redirect("Topic.aspx?tID=" + tID.ToString());
                }
                else
                {
                    
                }
            } 
        }

        protected bool IsMod()
        {
            return Modules.isMod(Modules.getConnectedUser());
        }

        protected void btnToggleSujet_Click(object sender, EventArgs e)
        {
            OleDbConnection connexion = new OleDbConnection(ConfigurationManager.ConnectionStrings[Constantes.DB_NAME].ConnectionString);
            connexion.Open();

            if (btnToggleSujet.Text == "Fermer le sujet")
            {
                OleDbCommand closeTopic = new OleDbCommand("UPDATE Sujets SET Ferme = 1", connexion);
                closeTopic.ExecuteNonQuery();
            }
            else
            {
                OleDbCommand openTopic = new OleDbCommand("UPDATE Sujets SET Ferme = 0", connexion);
                openTopic.ExecuteNonQuery();
            }
            connexion.Close();
            Response.Redirect(Request.RawUrl);
        }
    }
}